package com.meihua.baoleyi.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.meihua.baoleyi.R;
import com.meihua.baoleyi.base.BaseActivity;
import com.meihua.baoleyi.bean.BankInfo;
import com.meihua.baoleyi.bean.BankListResult;
import com.meihua.baoleyi.common.APIServer;
import com.meihua.baoleyi.common.MyApp;
import com.meihua.baoleyi.net.NetHelper;
import com.meihua.baoleyi.utils.ToastUtil;

import java.util.List;
import java.util.TreeMap;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 添加银行卡信息--手机号
 * Created by liming on 2017/10/18
 */
public class AddBankInfoPhoneActivity extends BaseActivity implements View.OnClickListener {

    private ImageView text_back;//返回
    private TextView text_title;//标题
    private TextView add_bank_info_type;//银行类型
    private EditText add_bank_info_phone_number;//手机号
    private CheckBox checkBoxNew;
    private TextView add_bank_info_next;//下一步
    private TextView tv_agree_rule;
    private String[] Card_Type;

    private String realName;
    private String banksCard;

    private List<BankInfo> mBankInfos;
    private List<BankInfo> data;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_bank_info_phone);
        //获取传参
        getParams();
        //初始化控件
        initView();
        //加载界面数据
        loadData();
        Card_Type = new String[]{};
    }


    /**
     * 加载界面需要的数据
     */
    private void loadData() {
        NetHelper.post(APIServer.BANKCARDLIST, new TreeMap<String, String>(), true, new NetHelper.HttpCallBack() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                BankListResult bean = NetHelper.getBeanForJson(BankListResult.class, s);
                if (bean == null) return;
                if (bean.getCode().equals("200") && bean.getData().size() > 0) {
                    //请求成功
                    data = bean.getData();
                    Card_Type = new String[data.size()];
                    for (int i = 0; i < data.size(); i++) {
                        Card_Type[i] = data.get(i).getBanks_name();
                    }
                }
            }
        });
    }

    /**
     * 获取界面传参
     */
    private void getParams() {
        realName = getIntent().getStringExtra("real_name");
        banksCard = getIntent().getStringExtra("banks_card");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Card_Type.clone();
    }

    /**
     * 加载布局
     */
    private void initView() {
        add_bank_info_phone_number = (EditText) findViewById(R.id.add_bank_info_phone_number);
        add_bank_info_type = (TextView) findViewById(R.id.add_bank_info_type);
        text_back = (ImageView) findViewById(R.id.text_back);
        text_title = (TextView) findViewById(R.id.text_title);
        add_bank_info_next = (TextView) findViewById(R.id.add_bank_info_next);
        tv_agree_rule = (TextView) findViewById(R.id.tv_agree_rule);
        text_title.setText("填写银行卡信息");
        checkBoxNew = (CheckBox) findViewById(R.id.checkBoxNew);
        text_back.setOnClickListener(this);
        add_bank_info_phone_number.addTextChangedListener(textWatcher);
        add_bank_info_next.setOnClickListener(this);
        tv_agree_rule.setOnClickListener(this);
        add_bank_info_type.setOnClickListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (data.getIntExtra("finish", 2) == 1) {
                setResult(1, data);
                finish();
            }
        }
    }

    /**
     * 输入框监听事件
     */
    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            if (add_bank_info_phone_number.getText().toString().length() == 11) {
                add_bank_info_next.setBackgroundResource(R.drawable.bank_next_bg_black);
                add_bank_info_next.setEnabled(true);
            } else {
                add_bank_info_next.setBackgroundResource(R.drawable.bank_next_bg_e0);
                add_bank_info_next.setEnabled(false);
            }

        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    };

    /**
     * 绑定点击事件
     *
     * @param view 被点击的控件
     */
    @Override
    public void onClick(View view) {
        final Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.add_bank_info_next://下一步
                //判断是否选中用户协议
                if (!checkBoxNew.isChecked()) {
                    ToastUtil.show(this, "请阅读并选中用户协议");
                    return;
                }

                //判断是否选择银行卡类型
                if (add_bank_info_type.getText().toString().trim().equals("")) {
                    ToastUtil.show(this, "请选择银行卡类型");
                    return;
                }
                String bankName = "";
                String bankId = "";

                //判断卡号是否为空
                if (!TextUtils.isEmpty(add_bank_info_type.getText())) {
                    bankName = add_bank_info_type.getText().toString();
                }
                for (BankInfo bankInfo : data) {
                    if(bankInfo.getBanks_name().equals(add_bank_info_type.getText().toString().trim())){
                        bankId =  bankInfo.getBank_id();
                    }
                }

                TreeMap<String, String> treeMap = new TreeMap<>();
                treeMap.put("user_id", MyApp.getInstance().getUser_id());//用户id
                treeMap.put("real_name", realName);//真实名称
                treeMap.put("banks_card", banksCard);//银行卡号
                treeMap.put("bank_id", bankId);//银行id
                treeMap.put("phone",  add_bank_info_phone_number.getText().toString().trim());//手机号
                final String finalBankId = bankId;

                //只可以请求一次
                add_bank_info_next.setBackgroundResource(R.drawable.bank_next_bg_e0);
                add_bank_info_next.setEnabled(false);

                showDialog();

                NetHelper.post(APIServer.BANKISTRUE,treeMap , true, new NetHelper.HttpCallBack() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        dismissDialog();
                        BankListResult bean = NetHelper.getBeanForJson(BankListResult.class, s);
                        if (bean == null) return;
                        if (bean.getCode().equals("200")) {
                            //界面参数并跳转
                            intent.setClass(AddBankInfoPhoneActivity.this, AddBankVerifyPhoneActivity.class);
                            intent.putExtra("real_name", realName);//真实名称
                            intent.putExtra("banks_card", banksCard);//银行卡
                            intent.putExtra("bank_id", finalBankId);//银行id
                            intent.putExtra("banks_type", add_bank_info_type.getText().toString());//银行类型
                            intent.putExtra("open_phone", add_bank_info_phone_number.getText().toString().trim());//手机号

                            add_bank_info_next.setBackgroundResource(R.drawable.bank_next_bg_black);
                            add_bank_info_next.setEnabled(true);
                            startActivityForResult(intent, 1);
                        }else {
                            ToastUtil.show(AddBankInfoPhoneActivity.this, bean.getMsg(),Toast.LENGTH_SHORT);
                            add_bank_info_next.setBackgroundResource(R.drawable.bank_next_bg_black);
                            add_bank_info_next.setEnabled(true);
                        }
                    }
                });

                break;
            case R.id.text_back://返回
                finish();
                break;
            case R.id.tv_agree_rule://打开用户协议界面
                Intent intent1 = new Intent(this, CommonWebActivity.class);
                intent1.putExtra("url", APIServer.HELP_CENTER_H5);
                startActivity(intent1);
                break;
            case R.id.add_bank_info_type://打开银行选择列表
                new MaterialDialog.Builder(AddBankInfoPhoneActivity.this)
                        .items(Card_Type)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                dialog.dismiss();
                                add_bank_info_type.setText(text);
                            }
                        })
                        .show();
                break;
        }
    }
}
